# @author:Wei Junjie
# @time:2024/5/24 17:20
# @file porn_hub.py
# --*--coding: utf-8 --*--
"""
模块说明
"""
import keyword
import re
import os
import requests
from fake_useragent import UserAgent
from bs4 import BeautifulSoup

VIDEO_URL =LOG_PATH_SAVE = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../sourceStore/VIDEO', 'Porn_Hub')
# 通过关键词查询到详细的页面信息
def search(keyword,page):
    cookies = {
        'accessAgeDisclaimerPH': '1',
    }
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    }
    params = {
        'search': keyword,
        'filter_category': '1',
        'page': page,
    }
    response = requests.get('https://cn.pornhub.com/video/search', params=params, cookies=cookies, headers=headers)
    return response

 # 正则匹配出所有的预览视频的地址和视频名称
def download_list(response):
    soup = BeautifulSoup(response.text, 'html.parser')
    pattern='data-mediabook="(.*?)".*?title="(.*?)"'
    data_list=re.findall(pattern, soup.prettify())
    return data_list


def download_page(url,keyword,title):
    pattern_obj=re.compile(r'[/\\*|?<>]')
    title=''.join(pattern_obj.split(title))
    url=''.join(url.split('amp;'))
    print(url)
    cookies = {
        'accessAgeDisclaimerPH': '1',
    }
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
    }
    # 尝试三次
    for item in range(3):
        try:
            response = requests.get(url, headers=headers,cookies=cookies)
            if response.status_code == 200:
                video_data =response.content
                # 判断文件是否存在
                if not os.path.exists(os.path.join(VIDEO_URL, keyword)):
                    os.mkdir(os.path.join(VIDEO_URL, keyword))

                with open(os.path.join(VIDEO_URL, keyword, title+'.webm'), 'wb') as f:
                    f.write(video_data)
        except Exception as e:
            print(e)
            continue


def main():
    keyword=input('请输入你要搜索的视频:\n')
    start_page=int(input('请输入你的起始页码:\n'))
    end_page=int(input('请输入你的终止页码:\n'))
    for page in range(start_page,end_page+1):
        response=search(keyword,page)

        data_list=download_list(response)

        for data in data_list:
            download_page(data[0],keyword,data[1])




if __name__ == '__main__':
    main()

